package cn.com.gridinfo.sooc.core.my.dao;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.JsonUtil;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.gridinfo.sooc.base.http.SoocIDao;
import cn.com.gridinfo.sooc.base.http.SoocNetResult;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.common.PublicConst;
import cn.com.gridinfo.sooc.common.UrlConst;
import cn.com.gridinfo.sooc.core.my.bean.UserInfo;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.course.bean.JRCourse;
import cn.com.gridinfo.sooc.core.my.course.bean.SCCourse;
import cn.com.gridinfo.sooc.core.my.msg.bean.CourseMsg;
import cn.com.gridinfo.sooc.core.my.msg.bean.Discuss;
import cn.com.gridinfo.sooc.core.my.msg.bean.MyNotice;
import cn.com.gridinfo.sooc.core.my.msg.bean.System;
import cn.com.gridinfo.sooc.core.my.note.bean.MyNote;
import cn.com.gridinfo.sooc.core.my.note.bean.MyNoteDetail;
import cn.com.gridinfo.sooc.core.my.order.bean.Order;
import cn.com.gridinfo.sooc.core.my.personal.activity.bean.UserPic;
import cn.com.gridinfo.sooc.core.my.setting.bean.GetQuestion;
import cn.com.gridinfo.sooc.core.my.setting.bean.MyAccount;
import cn.com.gridinfo.sooc.utils.HttpUrl;
import cn.com.gridinfo.sooc.utils.MD5;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 《我的》dao
 * Created by 刘晓晨 on 2015/12/8.
 */
public class MyDao extends SoocIDao {
    public String img;
    public String status = "";//确认是否成功的信息，  "0": 成功  "1":服务器维护 "2"：逻辑错误
    public String statusCode = "";//返回的信息
    public UserInfo userInfo = new UserInfo();//用户基本信息实体类
    public UserPic userPic = new UserPic();//更新头像
    public MyNotice notice = new MyNotice();//我的通知首页，课程通知
    public Discuss discuss = new Discuss();//我的通知首页，讨论通知
    public System system = new System();//我的通知，系统通知

    public MyNotice getNotice() {
        return notice;
    }

    public Discuss getDiscuss() {
        return discuss;
    }

    public System getSystem() {
        return system;
    }

    public Map<String, Map<String, String>> message;
    public List<JRCourse> jrCourseList = new ArrayList<>();//已加入课程实体类
    public List<SCCourse> scCourseList = new ArrayList<>();//已收藏的课程实体类
    public List<MyNote> myNoteList = new ArrayList<>();//我的笔记列表实体类
    public List<MyNoteDetail> myNoteDetailList = new ArrayList<>();//我的笔记详情
    public List<GetQuestion> getQuestionList = new ArrayList<>();//获取所有密保问题
    public List<MyAccount> account = new ArrayList<>();//获取账户信息
    public List<CourseMsg> courseMsg = new ArrayList<>();//获取课程通知
    private String studingCourseCount;//我在学课程
    private String studiedCourseCount;//已学完课程
    private List<Order> orderList;//订单列表

    public MyDao(SoocNetResult iNetResult) {
        super(iNetResult);
    }

    //请求成功返回数据
    @Override
    public void onRequestSuccess(JsonNode result, int requestCode) throws IOException {
        if (result == null) return;
        status = result.get("status").asText();
        statusCode = result.get("statusCode").asText();
        Log.d("result=" + result.toString());
        if (!status.equals("0")) return;
        switch (requestCode) {
            case CodeConst.GET_MYINFO:// 得到用户基本信息
                userInfo = JsonUtil.node2pojo(result.get("data"), UserInfo.class);
                //将信息存到本地
                Arad.preferences.putString(LocalMark.USER_HEADIMG.getName(), userInfo.getImg());
                Arad.preferences.putString(LocalMark.USER_TEL.getName(), userInfo.getCellphone());
                Arad.preferences.putString(LocalMark.USER_NICKNAME.getName(), userInfo.getUsername());
                Arad.preferences.putString(LocalMark.USER_EMAIL.getName(), userInfo.getEmail());
                Arad.preferences.putInteger(LocalMark.USER_SEX.getName(), userInfo.getSex());
                Arad.preferences.putString(LocalMark.USER_IDENTITYTYPE.getName().toString(), userInfo.getIdentityType());
                Arad.preferences.putString(LocalMark.USER_REALNAME.getName().toString(), userInfo.getXm());
                Arad.preferences.putString(LocalMark.USER_SFZJH.getName().toString(), userInfo.getSfzjh());
                Arad.preferences.flush();

                studiedCourseCount = result.get("data").get("studiedCount").asText();
                studingCourseCount = result.get("data").get("studingCount").asText();
                Log.d("我的信息------》" + userInfo);
                break;

            case CodeConst.JRCOURSE_FIRST://已加入课程
            case CodeConst.JRCOURSE_PULLUP://上拉
            case CodeConst.JRCOURSE_PUSHDOWN://下拉
                jrCourseList = JsonUtil.node2pojoList(result.get("data"), JRCourse.class);
                break;

            case CodeConst.SCCOURSE_FIRST://已收藏的课程
            case CodeConst.SCCOURSE_PULLUP://已收藏的课程 上拉
            case CodeConst.SCCOURSE_PUSHDOWN://已收藏的课程 下拉
                scCourseList = JsonUtil.node2pojoList(result.get("data"), SCCourse.class);
                break;

            case CodeConst.NOTELIST_FIRST://第一次请求笔记列表
            case CodeConst.NOTELIST_PULLUP://请求笔记列表 上拉
            case CodeConst.NOTELIST_PUSHDOWN://第一次请求笔记列表 下拉
                myNoteList = JsonUtil.node2pojoList(result.get("data"), MyNote.class);
                break;

            case CodeConst.NOTEDETAIL_FIRST://第一次请求笔记详情
            case CodeConst.NOTEDETAIL_PULLUP://上拉请求笔记详情
            case CodeConst.NOTEDETAIL_PUSHDOWN://下拉请求笔记详情
                myNoteDetailList = JsonUtil.node2pojoList(result.get("data"), MyNoteDetail.class);
                break;

            case CodeConst.COURSEMSG_FIRST://第一次请求课程通知
            case CodeConst.COURSEMSG_PULLUP://上拉请求课程通知
            case CodeConst.COURSEMSG_PUSHDOWN://下拉请求课程通知
                courseMsg = JsonUtil.node2pojoList(result.get("data"), CourseMsg.class);
                break;

            case CodeConst.UPDATEHEADIMG://修改头像
                Log.d("toutxiang success !");
                userPic = JsonUtil.node2pojo(result.get("data"), UserPic.class);
                Arad.preferences.putString("newPic", userPic.getUserpic());
                Arad.preferences.putString(LocalMark.USER_HEADIMG.getName(), userPic.getUserpic());
                Arad.preferences.flush();//新图片地址存本地
                break;

            case CodeConst.SHIMINGRENZHENG:// 实名认证
                MessageUtils.showImageShortToast(context, statusCode);
                break;

            case CodeConst.UPDATEINFO://修改用户信息
                Log.d("检测修改昵称");
                userInfo = JsonUtil.node2pojo(result.get("data"), UserInfo.class);
                break;

            case CodeConst.GETQUESTION://获取密保问题（列表）
                getQuestionList = JsonUtil.node2pojoList(result.get("data"), GetQuestion.class);
                break;

            case CodeConst.GETMYACCPUNT://获取账户信息
                account = JsonUtil.node2pojoList(result.get("data"), MyAccount.class);
                break;

            case CodeConst.MSGMAIN://通知主界面信息
                Log.d("是否有小红点 result:" + result);
                message = JsonUtil.node2pojo(result.get("data"), new TypeReference<Map<String, Map<String, String>>>() {
                });
//                if (result.get("data").has("notice")) {
//                    notice = JsonUtil.node2pojo(result.get("data").get("notice"), MyNotice.class);
//                    Log.d("NOTICE>>>>" + notice);
//                } else {
//                    notice = new MyNotice();
//                }
//                if (result.get("data").has("discuss")) {
//                    discuss = JsonUtil.node2pojo(result.get("data").get("discuss"), Discuss.class);
//                    Log.d("DISCUSS>>>>" + discuss);
//                } else {
//                    discuss = new Discuss();
//                }
//                if (result.get("data").has("system")) {
//                    system = JsonUtil.node2pojo(result.get("data").get("system"), System.class);
//                    Log.d("SYSTEM>>>>" + system);
//                } else {
//                    system = new System();
//                }
                break;

            //我的订单列表
            case CodeConst.MY_ORDER_LIST_FIRST:
            case CodeConst.MY_ORDER_LIST_LOADMORE:
            case CodeConst.MY_ORDER_LIST_REFRESH:
                orderList = JsonUtil.node2pojoList(result.get("data"), Order.class);
                break;
        }
    }

    public Map<String, Map<String, String>> getMessage() {
        return message;
    }

    /**
     * 初始化<我的>界面
     */
    public void myMainView() {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "getinfo", true);
        RequestParams params = new RequestParams();
        postRequest(url, params, CodeConst.GET_MYINFO);
    }

    /**
     * 已经加入的课程列表
     *
     * @param pageNo      页码
     * @param requestCode 请求吗
     * @param study       学习状态 1：已经学习完成 2：加入课程但是没有完成的课程
     */
    public void myAddCourse(int pageNo, int requestCode, String study) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "studyingList", true);
        Map<String, String> map = new HashMap<>();
        map.put("pageSize", 10 + "");
        map.put("pageNo", pageNo + "");
        map.put("study", study);
        getRequestForCode(url, map, requestCode);
    }

    /**
     * 显示收藏课程
     *
     * @param pageNo 页码
     */
    public void mySCCourse(int pageNo, int requestCode) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "collectionList", true);
        RequestParams params = new RequestParams();
        params.add("num", 10 + "");//每页十条
        params.add("page", pageNo + "");//第一页
        postRequest(url, params, requestCode);
    }

    /**
     * 删除收藏的课程
     *
     * @param kcid 课程id
     */
    public void deleteScCourse(String kcid) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "deleteCollection", true);
        RequestParams params = new RequestParams();
        params.add("kcid", kcid);
        postRequest(url, params, CodeConst.DELETECOURSE);
    }

    /**
     * 显示我的笔记列表
     *
     * @param pageNo 页码
     */
    public void myNote(int pageNo, int requestCode) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "selectCourses", true);
        RequestParams params = new RequestParams();
        params.add("num", 10 + "");//每页十条
        params.add("page", pageNo + "");//第一页
        postRequest(url, params, requestCode);
    }

    /**
     * 显示某一节课的笔记详情
     *
     * @param kcid   课程id
     * @param pageNo 页码
     */
    public void myNoteDetail(String kcid, int pageNo, int requestCode) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "note", true);
        RequestParams params = new RequestParams();
        params.add("kcid", kcid);
        params.add("my", "1");
        params.add("num", 10 + "");//每页十条
        params.add("page", pageNo + "");// 第一页
        postRequest(url, params, requestCode);
    }

    /**
     * 删除笔记
     *
     * @param bjid 笔记id
     */
    public void deleteNote(String bjid) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "deleteNote", true);
        RequestParams params = new RequestParams();
        params.add("bjid", bjid);
        postRequest(url, params, CodeConst.DELETENOTE);
    }

    /**
     * 更新用户头像
     */
    public void uploadPic(File file) {

        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "uploadpic", true);
        RequestParams params = new RequestParams();
        try {
            params.put("userpic", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        postRequest(url, params, CodeConst.UPDATEHEADIMG);
    }

    /**
     * 修改密码
     *
     * @param upass   旧密码
     * @param newPass 新密码
     */
    public void changePwd(String upass, String newPass) {
        Log.d("修改密码==========");
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "changePassword", true);//
        RequestParams params = new RequestParams();
        params.add("upass", MD5.encode(StringUtils.changeSpecialChar(upass)));
        params.add("newPass", MD5.encode(StringUtils.changeSpecialChar(newPass)));
        postRequest(url, params, CodeConst.CHANGEPWD);
    }

    /**
     * 实名认证
     *
     * @param xm           真实姓名
     * @param sfzjh        身份证号
     * @param identitytype 账号类型 3:学生 2：老师
     * @param pwd          用户密码
     */
    public void shiMing(String xm, String sfzjh, int identitytype, String pwd) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "auth", true);
        RequestParams params = new RequestParams();
        params.add("xm", xm);
        params.add("sfjzh", sfzjh);
        params.add("identitytype", identitytype + "");
        params.add("password", MD5.encode(StringUtils.changeSpecialChar(pwd)));
        postRequest(url, params, CodeConst.SHIMINGRENZHENG);
    }

    /**
     * * 修改用户信息
     *
     * @param nickname  昵称
     * @param cellphone 绑定手机号
     * @param emali     绑定的邮箱
     * @param sex       性别 0：女 1:男
     */
    public void updateInfo(String nickname, String cellphone, String emali, int sex) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "updateinfo", true);//
        Log.d("url" + url);
        RequestParams params = new RequestParams();
        params.add("nickname", nickname);
        Log.d("昵称" + nickname);
        params.add("cellphone", cellphone);
        params.add("email", emali);
        if (sex != -1) {
            params.add("sex", sex + "");
        }
        postRequest(url, params, CodeConst.UPDATEINFO);

    }

    /**
     * 获取验证码（绑定手机
     *
     * @param mobile 手机号码
     * @param type   短信类型:  1:密码找回  2:注册验证 3,绑定手机
     * @param dlxtbb 登录系统版本
     * @param dlsbxh 登录设备型号
     * @param yjbsm  硬件标识码
     */
    public void getYzm(String mobile, int type, String dlxtbb, String dlsbxh, String yjbsm) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "sms", true);//
        RequestParams params = new RequestParams();
        params.add("mobile", mobile);
        params.add("type", type + "");
        params.add("dlxtbb", dlxtbb);
        params.add("dlsbxh", dlsbxh);
        params.add("yjbsm", yjbsm);
        postRequest(url, params, CodeConst.GETSHOUJIYZM);
    }

    /**
     * 获取账户信息
     *
     * @param zhlx 账户类型  aliaccount 支付宝
     */
    public void myAccount(String zhlx) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "myAccount", true);
        RequestParams params = new RequestParams();
        params.add("zhlx", zhlx);
        postRequest(url, params, CodeConst.GETMYACCPUNT);
    }

    /**
     * 获取 我的消息 主界面数据
     */
    public void myMsgMain() {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "myMessage", true);
        RequestParams params = new RequestParams();
        postRequest(url, params, CodeConst.MSGMAIN);
    }

    /**
     * 获取我的消息-课程通知
     */
    public void myCourseMsg(int pageNo, int pageSize, int requestCode) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "notice", true);
        Log.d("获取课程通知的url>>>" + url);
        RequestParams params = new RequestParams();
        params.add("page", pageNo + "");
        params.add("num", 10 + "");
        postRequest(url, params, requestCode);
    }

    /**
     * （更换）绑定邮箱/手机号
     *
     * @param cellphone 手机号码
     * @param yzm       验证码
     * @param email     邮箱地址
     * @param password  用户密码
     */
    public void onBound(String cellphone, int yzm, String email, String password) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "updateAccount", true);//
        Log.d("绑定邮箱的url" + url);
        RequestParams params = new RequestParams();
        params.add("cellphone", cellphone);
        if (yzm != -2) {
            params.add("yzm", yzm + "");
        }
        params.add("email", email);
        params.add("password", MD5.encode(StringUtils.changeSpecialChar(password)));
        postRequest(url, params, CodeConst.ONBOUND);
    }

    /**
     * 获取所有密保问题的列表
     */
    public void getQuestion() {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "get_question", true);
        Log.d("到不到这里" + url);
        RequestParams params = new RequestParams();
        postRequest(url, params, CodeConst.GETQUESTION);
    }

    /**
     * 设置密保问题
     *
     * @param data 问题：答案
     */
    public void setQuestion(String data) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.User.toString(), "setQuestion", true);
        RequestParams params = new RequestParams();
        params.add("data", data);
        postRequest(url, params, CodeConst.SETQUESTION);
    }

    /**
     * 获得密保找回的问题
     *
     * @param uid 用户id
     * @param key 校验
     */
    public void mibaoQuestion(String uid, String key) {
        String url = HttpUrl.getHttpUrl(Arad.preferences.getString(LocalMark.SERVER_URL.getName()), UrlConst.Module.User.toString(), "getquestion");
        String url1 = Arad.preferences.getString(LocalMark.SERVER_URL.getName()) + "/index.php?s=apiv2/User/getquestion";
        RequestParams params = new RequestParams();
        params.add("uid", uid);
        params.add("key", MD5.encode(key));
        postRequest(url, params, CodeConst.MIBAOWENTI, PublicConst.NOT_NEED_TOKEN);
    }

    /**
     * 获取我的订单
     *
     * @param status      订单状态，0：全部，1：已付款  2：待付款 3：已取消，默认为0
     * @param pageNo      第几页，
     * @param pageSize    每页显示的条数
     * @param requestCode 请求码
     */
    public void getMyOrderList(String status, int pageNo, int pageSize, int requestCode) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "myOrders", true);
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        if (!StringUtils.isNull(status))
            map.put("status", status);
        getRequestForCode(url, map, requestCode);
    }

    /**
     * 取消订单
     *
     * @param orderId 订单号
     */
    public void cancelCourse(String orderId) {
        String url = HttpUrl.getHttpUrl(UrlConst.Module.Course.toString(), "cancelOrder", true);
        RequestParams params = new RequestParams();
        params.add("orderid", orderId);
        postRequest(url, params, CodeConst.ODRER_CANCELORDER);
    }

    public String getImg() {
        return img;
    }

    // 返回已加入课程列表信息
    public List<JRCourse> getJrCourseList() {
        return jrCourseList;
    }

    //返回已收藏的课程列表信息
    public List<SCCourse> getScCourseList() {
        return scCourseList;
    }

    // 返回 笔记列表
    public List<MyNote> getMyNoteList() {
        return myNoteList;
    }

    //返回，笔记详情
    public List<MyNoteDetail> getMyNoteDetailList() {
        return myNoteDetailList;
    }

    //所有密保问题
    public List<GetQuestion> getQuestions() {
        return getQuestionList;
    }

    //账户详情
    public List<MyAccount> getAccountList() {
        return account;
    }

    //课程通知
    public List<CourseMsg> getCourseMsg() {
        return courseMsg;
    }

    //通知主界面-课程通知
    public MyNotice getMyNotice() {
        return notice;
    }

    public String getStudingCourseCount() {
        return studingCourseCount;
    }

    public String getStudiedCourseCount() {
        return studiedCourseCount;
    }

    public List<Order> getOrderList() {
        return orderList;
    }
}
